<?php

namespace app\common\model\shop;

use app\common\utils\Utils;
use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'shop_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'type_text',
        'createtime_text',
        'thumb_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }

    public function getTypeList()
    {
        return ['0' => '价格面议', '1' => '在线展示'];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getThumbTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['thumb']) ? $data['thumb'] : '');
        return cdnurl($value, true);
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return Utils::time_format($value, $style='Y-m-d H:i:s');
    }

    public function getCategoryList() {
        $list = Category::where(['status'=> 'normal'])
            ->order('weigh desc createtime desc')
            ->field(['id', 'name'])
            ->select();

        return $list;
    }

    public function category()
    {
        return $this->belongsTo('app\common\model\shop\Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }



}
